package com.share.tool.maven.plugin.model;

import com.share.common.utils.EncryptUtil;
import com.share.common.utils.FileUtil;
import lombok.Data;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.util.List;

/**
 * Mojo注解的threadSafe属性默认为false 需要设置为true, 否则会报The following plugins are not marked @threadSafe警告
 */
@Data
@Mojo(name = "encryptClassEvent", threadSafe = true, defaultPhase = LifecyclePhase.PACKAGE)
public class EncryptClass extends AbstractMojo {
    @Parameter(property = "packageName", required = true)
    private String packageName;

    @Parameter(property = "outputDirectory", required = true)
    private String outputDirectory;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        //参数日志
        System.out.println("加密class文件packageName=" + packageName + ",outputDirectory=" + outputDirectory);

        //值初始化
        String packageNameDir = packageName.replaceAll("\\.", File.separator + File.separator); /*这里的替换需要注意正则*/

        //功能逻辑
        List<File> files = FileUtil.listFile(outputDirectory);
        for (File file : files) {
            String fileName = file.getAbsolutePath();
            if (fileName.contains(packageNameDir)) {
                byte[] bytes = FileUtil.readByte(file);
                if (!isClass(bytes)) {
                    System.err.println("文件之前已加密,请先clear,再install,否则密文文件未更新");
                    continue;
                }
                System.out.println("正在加密文件:" + fileName);
                byte[] encryptBytes = EncryptUtil.encrypt(bytes);
                FileUtil.writeByte(file, encryptBytes);
            }
        }
    }


    private boolean isClass(byte[] b) {
        if ((b[0] == -54) && (b[1] == -2) && (b[2] == -70) && (b[3] == -66)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            EncryptClass encryptClass = new EncryptClass();
            encryptClass.setPackageName("com.clx.rmp.mx.core");
            encryptClass.setOutputDirectory("D:\\open-project\\sharing\\risk-mx-pre\\rmp-mx\\target\\classes");
            encryptClass.execute();
        } catch (MojoExecutionException e) {
            e.printStackTrace();
        } catch (MojoFailureException e) {
            e.printStackTrace();
        }
    }
}
